<?php

namespace App\Service;

use App\Traits\ErrorTrait;
use Qiniu\Auth;

class CommonService
{
    use ErrorTrait;

    public $accessKey = 'XjZY_CzrRG1uwkSsNfFRcet3Ec7oj00_H5Xa3FhQ';
    public $secretKey = '9WkKGKvdf-pPGU2EVsacOWRTldSlER-2M4pmV4-6';
    public $bucket = 'aixin';
    public $domain = 'static.i-yc.com';

    private $picType = array(
        "image/jpeg" => ".jpg",
        "image/png" => ".png",
        "image/gif" => ".gif"
    );

    public function getQiniuToken($fileName = '')
    {
        $auth = new Auth($this->accessKey, $this->secretKey);
        if ($fileName) {
            $token = $auth->uploadToken($this->bucket, null, 3600, ['saveKey' => $fileName]);
        } else {
            $token = $auth->uploadToken($this->bucket);
        }
        return $token;

    }

    public function picToken($picType)
    {
        if (!array_key_exists($picType, $this->picType)) {
            $this->error = '图片类型不支持';
            return false;
        }
        $fileName = date('ymdHis') . mt_rand(100000, 999999)
            .$this->picType[$picType];
        $token = $this->getQiniuToken($fileName);
        $picPath = 'http://' . $this->domain . '/' . $fileName;
        return [
            'token' => $token,
            'pic' => $picPath
        ];
    }
}